<?php

namespace app\api\controller\v2;

use app\api\controller\Common;
use app\service\Token;
use app\api\model\ConfigSystem as Config;
use app\service\UserIntimate as UserIntimateService;
use think\Db;
use think\Request;

class Privacyzone extends Common {
    public $params = null;
    public function __construct(Request $request = null) {
        parent::__construct($request);
        $this->params = getRsaPostParamArr2();
    }

    public function memberInfo()
    {
        if (!$this->member) return $this->miss('');
        $this->params['timestamp'] = $this->params['timestamp'] ?? 0;
        $user_id = $this->member['id'];
        $data = Db::name('user')->master()->where(['reg'=>2, 'authcode'=>$user_id])->find();
        $timenow = time();
        if (!$data) {
        	$data['reg'] = 2;
        	$data['authcode'] = $user_id;
        	$data['unpush'] = 1;
        	$data['name'] = 'FM-'.rand(1000,9999);
        	$data['head_100'] = $data['head_300'] = $data['head_portrait'] = '/public/style/api/img/avatar/'.($this->member['sex']=='女'?'female':'male').'/a'.rand(1, 16).'.png';
        	$data['password'] = md5($timenow);
        	$data['quality'] = $this->member['quality'] ?? 0;
        	$data['device_id'] = $this->member['device_id'];
        	$data['sex'] = $this->member['sex'];
        	$data['age'] = $this->member['age'];
        	$data['last_login_time'] = $this->member['last_login_time'];
        	$data['id'] = Db::name('user')->insertGetId($data);
        	if (!$data['id']) return $this->miss('服务异常,请稍后重试');
        } else {
            $update['sex'] = $this->member['sex'];
            $update['age'] = $this->member['age'];
            $update['entertainment'] = $this->member['entertainment'];
            $update['last_login_datetime'] = $this->member['last_login_datetime'];
            Db::name('user')->where(['id'=>$data['id']])->update($update);
        }


        $tokenData = array(
            'userid' => $data['id'],
            'time' => $data['last_login_time'],
        );
        $token = Token::createToken($tokenData);
        if($token['status']==200){
            $token = $token['token'];
        }

        return json(['code' => 200, 'id' => (int)$data['id'], 'token'=>$token]);
    }


    public function category()
    {
    	$top_id = Db::name('config_system')->where(['title'=>'privacy_categroy_id'])->value('content');
    	$data = Db::name('dymanic_category')->where(['parent_id'=>$top_id, 'is_hide'=>0])->order('des desc, id asc')->field('id,name')->select();

    	return $this->pass($data);
    }

    public function userInfo()
    {
        $touserid = $this->params['touserid'] ?? 0;
    	$data = Db::name('user')
    				->alias('a')
    				->join('user b', 'a.authcode=b.id')
    				->where(['a.id'=>$touserid, 'a.reg'=>2])
    				->field('a.id,a.name,a.head_portrait,b.sex,b.entertainment,b.entertainment_child, b.age,b.id real_id,b.register_datetime')
    				->find();
        $mine_privacy = Db::name('user')->where(['reg'=>2,'authcode'=>$this->member['id']])->find();
        $data['comment_num'] = Db::name('dycomment')->where(['userid'=>$touserid, 'shenhe'=>1])->cache('Privacyzone:userInfo:comment_num:'.$touserid, 60)->count();
        $data['zan_num'] = Db::name('dymanic_userthumbsup')->where(['userid'=>$touserid])->cache('Privacyzone:userInfo:zan_num:'.$touserid, 60)->count();
		$data['dy_num'] = Db::name('dymanic')->where(['userid'=>$touserid, 'shenhe'=>1])->cache('Privacyzone:userInfo:dy_num:'.$touserid, 60)->count();

		$touserid_real = $data['real_id'];
		$register_datetime = $data['register_datetime'];
		unset($data['real_id']);
		unset($data['register_datetime']);

        Db::name('user')->where(['id' => $touserid])->setInc('see');

        $data['configPersonal'] = $configPersonal = Db::name('config_personal')->where(['user_id' => $touserid_real])->field('chat_price,voice_switch,voice_price,video_switch,video_price')->find();

        if ($data['configPersonal']) {
            if ($data['configPersonal']['chat_price'] && $data['configPersonal']['chat_price'] > 2) {
                $data['configPersonal']['chat_price'] = 2;
            }
            if ($data['configPersonal']['voice_price'] && $data['configPersonal']['voice_price'] > 15) {
                $data['configPersonal']['voice_price'] = 15;
            }
            if ($data['configPersonal']['video_price'] && $data['configPersonal']['video_price'] > 30) {
                $data['configPersonal']['video_price'] = 30;
            }
        }

        $Map = $this->member['id'] < $touserid_real ? [
            'user_id' => $this->member['id'],
            'another_id' => $touserid_real,
        ] :  [
            'user_id' => $touserid_real,
            'another_id' => $this->member['id'],
        ];

        // 聊天打折
        $overpayscale = 0;
        // 获取所有关联账号的总支付
        $overpayscale = UserIntimateService::Count($this->member['id'], $touserid_real, true);
        if ($overpayscale) {
            $chat_scale['scale'] = $overpayscale;
        } else {
            $chat_scale = Db::name('limit_chat_price')->where($Map)->find();
        }
        if ($chat_scale) {
            $data['configPersonal']['chat_price'] = isset($data['configPersonal']['chat_price']) ? round($data['configPersonal']['chat_price'] * $chat_scale['scale'] / 100, 2) : 0;
            $data['configPersonal']['voice_price'] = isset($data['configPersonal']['voice_price']) ? round($data['configPersonal']['voice_price'] * $chat_scale['scale'] / 100, 2) : 0;
            $data['configPersonal']['video_price'] = isset($data['configPersonal']['video_price']) ? round($data['configPersonal']['video_price'] * $chat_scale['scale'] / 100, 2) : 0;
        }


        $data['is_payer'] = true;
        $configTwoWayCharge = Config::index('two_way_charge');
        if ($configTwoWayCharge['two_way_charge_status'] == 1 && ((strtotime($this->member['register_datetime']) > strtotime($configTwoWayCharge['two_way_charge_reg_time'])) || (strtotime($register_datetime) > strtotime($configTwoWayCharge['two_way_charge_reg_time'])))) {
            
            $ChatChargeRecords = Db::name('chat_charge_records')->master(true)->where($Map)->find();
            if ($ChatChargeRecords && $ChatChargeRecords['state']) {
                $data['is_payer'] = $this->member['id'] == $ChatChargeRecords['payer'];
            }
        }


        $data['entertainment_text'] = Db::name('user_entertainment')->where(['role_type'=>$data['entertainment']])->value('name');
        if ($data['entertainment_child']) {
            $additionValue = 1;
            $numbersArray = explode(',', $data['entertainment_child']);
            $resultArray = array_map(function ($number) use ($additionValue) {
                return $number + $additionValue;
            }, $numbersArray);
            $resultString = implode(',', $resultArray);

            $data['entertainment_child_text'] = Db::name('user_entertainment')->where(['id'=>['in',$resultString]])->column('name');
            $data['entertainment_child_text'] = implode('|',$data['entertainment_child_text']);
        }

        $data['is_blacklist'] = Db::name('blacklist')->where(['user_id'=>$mine_privacy['id'], 'to_user'=>$touserid])->find();
        $data['is_blacklist'] = $data['is_blacklist'] ? true : false;


		return $this->pass($data);
    }
}